package com.example.pages;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

import com.example.HW.User;
import com.google.common.collect.Lists;

public class UserManagementPage extends InternalPage {
	
	@FindBy(css="input#username")
	public WebElement userNameField1;
	
	@FindBy(css = "input.required.email")
	public WebElement emailField1;
	
	@FindBy(css = "input[id = 'password']")
	public WebElement passwordField1;
	
	@FindBy(css = "input[id = 'password2']")
	public WebElement passwordAgainField1;
	
	@FindBy(css = "input[name=\"submit\"]")
	public WebElement saveButton1;
	
	@FindBy(css = "div.content h2")
	public WebElement userManagementText;
	
	@FindBy(css = "div#user-list table > tbody > tr")
	public List<WebElement> userRows;
	
	public boolean thereIsUserManagement() {
		return userManagementText.isDisplayed();
	}
	
	public UserManagementPage createUser(User user) {
		
		userNameField1.sendKeys(user.name);
		emailField1.sendKeys(user.email);
		passwordField1.sendKeys(user.password);
		passwordAgainField1.sendKeys(user.password);
		saveButton1.click();
		return MyPageFactory.getPage(driver, UserManagementPage.class);
	}

	public List<User> getUsers() {
		List<User> users = Lists.newArrayList();
		for (WebElement row: userRows) {
			users.add(convertRowToUser(row));
		}
		return users;
	}

	private User convertRowToUser(WebElement row) {
		List<WebElement> cells = row.findElements(By.tagName("td"));
		return new User()
		.withName(cells.get(1).getText())
		.withEmail(cells.get(2).getText())
		.withRole(cells.get(3).getText());
	}

}
